package net.alan.modules.service.impl;

import net.alan.common.constants.ENoticeType;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.repository.NoticeRepository;
import net.alan.modules.service.INoticeService;
import net.alan.modules.service.IProjectService;
import net.alan.modules.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Service
public class NoticeServiceImpl extends BaseServiceImpl implements INoticeService {
    private static final Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);
    @Autowired
    private NoticeRepository noticeRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private IProjectService projectService;

    @Override
    public JpaRepository getJpaRepository(Class<?> cla) {
        return noticeRepository;
    }

    @Override
    public Page<Notice> findByUserId(Integer userId, PageModel pageModel) {
        return noticeRepository.findByUserId(userId, pageModel.getPageable(Sort.Direction.DESC, "id"));
    }

    @Override
    public Result ok(Integer id) {
        Notice notice = noticeRepository.getOne(id);
        notice.setReaded(true);
        this.noticeRepository.save(notice);
        return ResultUtil.success();
    }

    @Override
    public Result okProject(Integer id) {
        Notice notice = noticeRepository.getOne(id);
        notice.setReaded(true);
        this.noticeRepository.save(notice);


        return ResultUtil.success();
    }

    @Override
    public Result noticeAll(String content) {
        List<User> list = userService.findAll(User.class);
        if (list != null) {
            for (User user : list) {
                addNotice(content, ENoticeType.sys, 0, user.getId());
            }
        }
        return ResultUtil.success();
    }

    public void addNotice(String content, ENoticeType noticeType, Integer refId, Integer userId) {
        Notice notice = new Notice();
        notice.setContent(content);
        notice.setNoteType(noticeType.name());
        notice.setRefId(refId);
        notice.setUserId(userId);
        notice.setFromUserId(WebContextUtil.getUserId());
        this.noticeRepository.save(notice);
    }

    @Override
    public int countUnRead(Integer userId) {
        return this.noticeRepository.countByUserIdAndReadedFalse(userId);
    }
}
